// Copyright Epic Games, Inc. All Rights Reserved.

#include "iothreadpool.h"

#include <zencore/except.h>

#if ZEN_PLATFORM_WINDOWS

namespace zen {

WinIoThreadPool::WinIoThreadPool(int InThreadCount, int InMaxThreadCount)
{
	ZEN_ASSERT(InThreadCount);

	if (InMaxThreadCount < InThreadCount)
	{
		InMaxThreadCount = InThreadCount;
	}

	m_ThreadPool = CreateThreadpool(NULL);

	SetThreadpoolThreadMinimum(m_ThreadPool, InThreadCount);
	SetThreadpoolThreadMaximum(m_ThreadPool, InMaxThreadCount);

	InitializeThreadpoolEnvironment(&m_CallbackEnvironment);

	m_CleanupGroup = CreateThreadpoolCleanupGroup();

	SetThreadpoolCallbackPool(&m_CallbackEnvironment, m_ThreadPool);

	SetThreadpoolCallbackCleanupGroup(&m_CallbackEnvironment, m_CleanupGroup, NULL);
}

WinIoThreadPool::~WinIoThreadPool()
{
	// this will wait for all callbacks to complete and tear down the `CreateThreadpoolIo`
	// object and release all related objects
	CloseThreadpoolCleanupGroupMembers(m_CleanupGroup, /* cancel pending callbacks */ TRUE, nullptr);
	CloseThreadpoolCleanupGroup(m_CleanupGroup);
	CloseThreadpool(m_ThreadPool);
	DestroyThreadpoolEnvironment(&m_CallbackEnvironment);
}

void
WinIoThreadPool::CreateIocp(HANDLE IoHandle, PTP_WIN32_IO_CALLBACK Callback, void* Context, std::error_code& ErrorCode)
{
	ZEN_ASSERT(!m_ThreadPoolIo);

	m_ThreadPoolIo = CreateThreadpoolIo(IoHandle, Callback, Context, &m_CallbackEnvironment);

	if (!m_ThreadPoolIo)
	{
		ErrorCode = MakeErrorCodeFromLastError();
	}
}

}  // namespace zen

#endif
